package com.xfp.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.xfp.mapper.PartnerMapper;
import com.xfp.method.pageTotal;
import com.xfp.pojo.dto.PartnerDto;
import com.xfp.pojo.dto.PartnerQueryDto;
import com.xfp.pojo.entity.Partner;
import com.xfp.pojo.vo.PartnerQueryVo;
import com.xfp.pojo.vo.PartnerVo;
import com.xfp.service.PartnerService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;

@Service
public class PartnerServiceImp implements PartnerService {

    @Autowired
    private PartnerMapper partnerMapper;

    /**
     * 新增合作商
     * @param dto
     */
    @Override
    public void insert(PartnerDto dto) throws Exception {
        Partner partner = new Partner();
        BeanUtils.copyProperties(dto,partner);
        int n = partnerMapper.insert(partner);
        if(n!=1){
            throw new Exception("合作商添加失败");
        }
    }

    /**
     * 分页查询实现
     * @param dto
     * @return
     */
    @Override
    public PartnerQueryVo page(PartnerQueryDto dto) throws Exception {
        //校验排除异常数据
        dto.check();
        //使用插件
        PageHelper.startPage(dto.getPageIndex(),dto.getPageSize());
        Page<PartnerVo> page = partnerMapper.page(dto);
        page.forEach(p->{
            int n = partnerMapper.countVm(p.getId());
            p.setVmCount(n);
        });
        Long l = pageTotal.total(page.getTotal(), dto.getPageSize());
        return new PartnerQueryVo(dto.getPageIndex(),dto.getPageSize(),l,page.getTotal(),page.getResult());
    }

    /**
     * 修改合作商
     * @param id
     * @param dto
     */
    @Override
    public void update(Integer id, PartnerDto dto) throws Exception {
        //查询是否存在该合作商
        Partner exist = partnerMapper.findById(id);
        if(exist == null){
            throw new Exception("该合作商不存在");
        }
        Partner partner = new Partner();
        BeanUtils.copyProperties(dto,partner);
        partner.setId(id);
        int n = partnerMapper.update(partner);
        if(n!=1){
            throw new Exception("修改合作商失败");
        }
    }

    /**
     * 获取合作商基本信息
     * @param id
     * @return
     */
    @Override
    public PartnerVo findById(Integer id) throws Exception {
        Partner partner = partnerMapper.findById(id);
        if(partner == null){
            throw new Exception("获取合作商失败");
        }
        PartnerVo vo = new PartnerVo();
        BeanUtils.copyProperties(partner,vo);
        return vo;
    }

    /**
     * 根据id删除合作商
     * @param id
     */
    @Override
    public void delete(Integer id) throws Exception {
        int n = partnerMapper.delete(id);
        if(n!=1){
            throw new Exception("删除合作商失败");
        }
    }

    /**
     * 修改合作商密码
     * @param id
     */
    @Override
    public void restPwd(Integer id) {
        partnerMapper.restPwd(id);
    }
}
